package com.cade.agriculturemall.util;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

import com.cade.agriculturemall.App;

/**
 * Created by Lobby on 2017/11/9.
 */
 public class ToastUtils {


    private static Toast mToast ;
    private static Handler mHandler = new Handler();
    private static Runnable r = new Runnable() {
        @Override
        public void run() {
            mToast.cancel();
        }
    } ;

    /**
     * 自定义toast，重复点击时，会直接替换文本，不会重新创建新的Toast并加入队列中一条条显示
     * @param context
     * @param text
     * @param duration
     */
    public static void showToast(Context context, String text, int duration) {
        mHandler.removeCallbacks(r);
        if (mToast != null) {
            mToast.setText(text);
        } else {
            mToast = Toast.makeText(context,text,Toast.LENGTH_SHORT);
        }
        mHandler.postDelayed(r,duration) ;
        mToast.show();
    }

    /**
     * 防重复点击的toast，即便是帕金森患者也不会导致toast一直显示着
     * @param text
     */
    public static void showToast(String text) {
        showToast(App.getInstance().getApplicationContext(),text,1000);
    }

    public static void showToast(Context context,int resId,int duration) {
        showToast(context,context.getResources().getString(resId),duration);
    }


    public static void show(CharSequence text) {
        Toast.makeText(App.getInstance().getApplicationContext(), text, Toast.LENGTH_SHORT).show();
    }

    /**
     * 显示土司的工具类,安全的工具类可以在任意线程里面显示
     * @param activity
     * @param text
     */
    public static void show(final Activity activity, final CharSequence text) {
        if ("main".equalsIgnoreCase(Thread.currentThread().getName())) {
            if (activity == null){
                return;
            }
            Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
        } else {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    /**
     * 显示土司的工具类,安全的工具类可以在任意线程里面显示
     * @param activity
     * @param text
     * @param length 显示的时常
     */
    public static void show(final Activity activity, final CharSequence text, final int length) {
        if ("main".equalsIgnoreCase(Thread.currentThread().getName())) {
            Toast.makeText(activity, text, length).show();
        } else {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, text, length).show();
                }
            });
        }
    }
}

